package cn.edu.zsc.study.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.LocalDateTime;

/**
 * @author harry_yao
 */
@AllArgsConstructor
@RestControllerAdvice
public class ApiExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(ApiExceptionHandler.class);

    private final ObjectMapper objectMapper;

    @ExceptionHandler(value = {ConstraintException.class})
    public ResponseEntity<Object> handleException(ConstraintException ex) {
        logger.error("ConstraintException: {}", ex.getMessage());
        return new ResponseEntity<>(new ExceptionResult(ex.getMessage(), HttpStatus.BAD_REQUEST.value(), LocalDateTime.now()),
            HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(value = {NotExistException.class})
    public ResponseEntity<Object> handleException(NotExistException ex) {
        logger.error("NotExistException: {}", ex.getMessage());
        return new ResponseEntity<>(new ExceptionResult(ex.getMessage(), HttpStatus.NOT_FOUND.value(), LocalDateTime.now()),
            HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(value = {StateException.class})
    public ResponseEntity<Object> handleException(StateException ex) {
        logger.error("StateException: {}", ex.getMessage());
        return new ResponseEntity<>(new ExceptionResult(ex.getMessage(), HttpStatus.NOT_FOUND.value(), LocalDateTime.now()),
            HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(value = {UserHasNoIdentityException.class})
    public ResponseEntity<Object> handleException(UserHasNoIdentityException ex) {
        logger.error("UserHasNoIdentityException: {}", ex.getMessage());
        return new ResponseEntity<>(new ExceptionResult(ex.getMessage(), HttpStatus.UNAUTHORIZED.value(), LocalDateTime.now()),
            HttpStatus.UNAUTHORIZED);
    }

    @ExceptionHandler(value = {ValidateException.class})
    public ResponseEntity<Object> handleException(ValidateException ex) {
        logger.error("ValidateException: {}", ex.getMessage());
        return new ResponseEntity<>(new ExceptionResult(ex.getMessage(), HttpStatus.UNAUTHORIZED.value(), LocalDateTime.now()),
            HttpStatus.UNAUTHORIZED);
    }

    @ExceptionHandler(value = {ApiException.class})
    public ResponseEntity<Object> handleException(ApiException ex) {
        logger.error("ApiException: {}", ex.getMessage());
        return new ResponseEntity<>(new ExceptionResult(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.value(), LocalDateTime.now()),
            HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
